﻿//-------------------------------------------------------------------------
///-----------------task_mgr---------------------------------------------
///-----------------task_mgr-----------------------------------------
///-----------------2024/01/02---by mv------------------------------
//-------------------------------------------------------------------------
#include "task_mgr.h"
//#include "protocol/ipc_message_header.hpp"
#include "json/json.h"
#include <time.h>
#include "cmd/http_curl/httpCurl.h"

#include "../push/udp_session.h"
#include "../sharememory/shm_session.h"
//process
#include "../common/_processdata.h"
#include"../common/mvPubApi.h"

//ip mac
#include <iostream>
#include <sys/types.h>
#include <ifaddrs.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fstream>
#include <string>
#include<vector>
#include<thread>
//-------------------------------------------------------------------------------------

std::mutex task_info_mx;
std::unordered_map<std::string, std::function<bool(Json::Value&)>> m_func_map;

//-------------------------------------------------------------------------------------
void recvShmMsg(const int iFlag, const std::string& recv_messageg) {
	mv::TaskMgr::Instance().getTasIpcPool()->async([iFlag,recv_messageg]() {
        //接收硬件控制信息
        mv::TaskMgr::Instance().receiveSharememoryData(iFlag,recv_messageg);
		});
}

void recvPushConnect(int iStatus) {

    mv::TaskMgr::Instance().getTasIpcPool()->async([iStatus]() {
        //更新连接状态
        bool bUdpConnect = static_cast<bool>(iStatus);
        mv::TaskMgr::Instance().receivePushConnStatus(bUdpConnect);
    });
}

void recvPushData(int iType, int iCmd, std::string sRevData) {
        
    mv::TaskMgr::Instance().getTasIpcPool()->async([iType,iCmd,sRevData]() {
            //业务切换
        mv::TaskMgr::Instance().receiveServiceData(iType,iCmd,sRevData);
    });
}

void mv::TaskMgr::receivePushConnStatus(bool bConnect) {
    m_bUDPConnect = bConnect;

    if (!m_bUDPConnect) {
        InfoL << "UDP Push 通讯断开连接";
        awtkUISwitch(CLOSE_PAGE);
        hardwareLightCtrl(Light_Red);
    } else {
        InfoL << "UDP Push 通讯已连接";
        if (!m_bOCRConnect) {
            if (m_iOCRState == -1) {
                InfoL << "等待查询下位机,OCR连接状态<";
            } else {
                InfoL << "OCR未连接,切换至设备故障页面<";
                awtkUISwitch(EQUIPMENT_ABNORMALITY);
                hardwareLightCtrl(Light_Red);
            }
        } else if (!m_bAcquisitionCab) {
            if (m_iCurrentProcess != EQUIPMENT_ABNORMALITY) {
                InfoL << "下位机未连接,切换至设备故障页面<";
                awtkUISwitch(EQUIPMENT_ABNORMALITY);
                hardwareLightCtrl(Light_Red);
            }
        } else {
            awtkUISwitch(WELCOME_PAGE);
        }
    }
}

//接收车道业务端切换业务信息
void mv::TaskMgr::receiveServiceData(const int iType, const int iCmd, const std::string sRevData) {
    InfoL << "Push type:" << iType << ",cmd: " << iCmd << ",revData:" << sRevData;
    if (iType == 2) {           //
        if ((iCmd == 0) || (iCmd == 2)) {
            awtkUISwitch(WELCOME_PAGE);
        }
        else if (iCmd == 1) {
            awtkUISwitch(GET_VEHICLE_INFO);
        }
        else if (iCmd == 0) {
            awtkUISwitch(CLOSE_PAGE);
        }
        else if(iCmd == 6) {// 6：启用当前屏
            awtkUISwitch(WAIT_PAGE);
        }
    } else if(iType == 3) { //车牌识别
        if(iCmd == 0){//车牌识别成功
            m_sVehicleNo = sRevData;
        }
        else if(iCmd == 1) {//车牌识别失败
            awtkUISwitch(GET_VEHICLE_FAILED);
        }
        else if(iCmd == 2) {//车牌号未备案
            awtkUISwitch(GET_VEHICLE_NOT_FILED);
        }
    } else if(iType == 5) {// 读卡控制
        if(iCmd == 0 || iCmd == 1) {// 0：开始读司机卡 1：证件读取中，请勿移动
            awtkUISwitch(CARD_READING);
        }
        else if(iCmd == 2) {// 2：司机读卡成功
            //切换请取回证件
            awtkUISwitch(CARD_READING_SUC);
        }
        else if(iCmd == 3) {// 3：司机读卡失败
            awtkUISwitch(CARD_READING_FAILED);
        }
        else if(iCmd == 4) {// 4：证件过期
            awtkUISwitch(CARD_EXPIRED);
        }
        else if(iCmd == 5) {// 2：司机读卡成功
            //切换请取回证件
            awtkUISwitch(CARD_READING_SUC);
        }
    } else if(iType == 6) {// 人脸控制
        if(iCmd == 0) {// 0：开始人脸认证
            awtkUISwitch(FACE_REC);
        }
        else if(iCmd == 2) {// 2：面相比对超时
            awtkUISwitch(FACE_EXPIRED);
        }
    } else if(iType == 8) {//业务状态
        if(iCmd == 1) {//1：放行
            //if ((m_iOCRDeviceState == OCR_Scanning) && (m_iCurrentProcess == CARD_READING_SUC)) {
            if ((m_iOCRDeviceState == OCR_Scanning) && (m_bWaitingRelease)) {
                InfoL << "缓存当前流程状态: VEHICLE_PASSAGE";
                m_iCachedProcess = VEHICLE_PASSAGE;
            } else {
                awtkUISwitch(VEHICLE_PASSAGE);
            }
        }
        else if(iCmd == 3) {//3：退车
           // if ((m_iOCRDeviceState == OCR_Scanning) && (m_iCurrentProcess == CARD_READING_SUC)) {
             if ((m_iOCRDeviceState == OCR_Scanning) && (m_bWaitingRelease)) {
                InfoL << "缓存当前流程状态: VEHICLE_EXIT_CHANNEL";
                m_iCachedProcess = VEHICLE_EXIT_CHANNEL;
            } else {
                awtkUISwitch(VEHICLE_EXIT_CHANNEL);
            }
        }
    } else if(iType == 9) {//虹膜控制
        if(iCmd == 0){//开始虹膜认证
            awtkUISwitch(IRIS_REC);
        }
        else if(iCmd == 2) {//虹膜比对超时
            awtkUISwitch(IRIS_FAILED);
        }
    } else if(iType == 10) {//机械臂控制
        if(iCmd == 1){//升降开始下降
            processSwitch(Process_Start,std::stoi(sRevData));
            InfoL << "切换到乘客摇下车窗页面";
             pubAwtkProcessEvent(Psg_Roll_Window);
        }
        else if(iCmd == 2) {//伸缩缩回
            processSwitch(Process_End,0);
            InfoL << "切换到首页";
            pubAwtkProcessEvent(WELCOME_PAGE);
        }
    } else if (iType == 12) {
        m_iStartNumOfPerson = iCmd;
        InfoL << "平台提前申报通行人数: " <<  std::to_string(m_iStartNumOfPerson);
    }
    //拓展测试指令  20240119
    else if (iType == 13) {         //车窗检测完成，开始伸出，下发高度
        if (m_iCurrentProcess == GET_VEHICLE || m_iCurrentProcess == Process_Start) {
            m_iLeftHighAltitude = 5000;
        }
    } else if (iType == 14) {       //伸出到位，切换按人数
        if ((m_iCurrentProcess == GET_VEHICLE || m_iCurrentProcess == Process_Start) && (m_iStartNumOfPerson > 0)) {
            //有后台提前申报，切换到刷证页面,并开始进入计时阶段，计时线程开启
            awtkUISwitch(CARD_READING);
        } else {
            //无后台提前申报，切换到按人数页面
            awtkUISwitch(Enter_Num_People);
        }
    } else if (iType == 15) {       //左舵时上传人数，并上传当前升降机高度，切换到刷证界面，并开始进入计时阶段，计时线程开启。如果提前申报了人数，不经过15步骤
        if (m_iCurrentProcess == Enter_Num_People) {
            m_iNumberOfPerson = iCmd;

            //测试按键人数，测试完成后删除
            if (m_iPeopleNumTest == 1) {
                awtkUISwitch(CARD_READING);
            } else if (m_iPeopleNumTest == 2) {
                awtkUISwitch(Psg_Roll_Window);
                triggerOnceThread(CARD_READING);
            } else {
                awtkUISwitch(CARD_READING);
            }

            pushPersonNumberData(std::to_string(m_iPeopleNumTest),std::to_string(m_iLeftHighAltitude));
            
            if (m_iPeopleNumTest == 1) {
                m_iPeopleNumTest = 2;
            } else {
                m_iPeopleNumTest = 1;
            }
            //----------------------------------------------------------
        }
    } else if (iType == 16) {       //人脸采集完成，模拟上传人脸数据
        facePubEvent();
    } else if (iType == 17) {       //虹膜采集完成，模拟上传虹膜数据
        irisPubEvent();
    } else if (iType == 18) {
                //TODO回退流程，人脸虹膜流程回退到刷证，刷证回退到按人数，按人数无响应，清除对应缓存
        if (m_iCurrentProcess == FACE_REC || m_iCurrentProcess == IRIS_REC) {
            //关闭虹膜采集，发送切换到刷证流程,清除刷证数据，文件，以及采集的人脸数据
            backToSwipeProcess();
        } else if ((m_iCurrentProcess == CARD_READING) || (m_iCurrentProcess == CARD_READING_FAILED) || 
            (m_iCurrentProcess == CARD_STOP_MOVE)) {
            if (cfgInfo.iDevDirect == 0) {
                backToEnterPeopleProcess();
            } else {
                InfoL << "右舵不处理回退到申报人数流程，跳过操作";
            }
        } else {
            InfoL << "非回退处理流程，跳过操作";
        }
    }
}

void mv::TaskMgr::processSwitch(const int iCmd, const int iHeight) {
    InfoL << "<<<<<<<<<<<<<<<<<<<<<<<<<<";
    if (iCmd == Process_Start) {
        if (m_bProcessStart) {
            InfoL << "采集流程中，跳过业务流程开始指令操作";
            return;
        }
        InfoL << "业务流程开始,业务控制高度为: " <<  iHeight;
        if (cfgInfo.iDevDirect == 1) {
            //TODO传入升降高度 右舵不进行车窗检测. 当平台提前录入人数后,右舵发送高度为0，要进行车窗检测
            if (iHeight == 0) {
                hardwareProcessCtrl(true,cfgInfo.iCarWindowDetect,cfgInfo.iDevDirect + 1);
            } else {
                hardwareHeightCtrl(iHeight);
            }
        } else {
            //TODO发送左舵右舵标识 下降指令
            hardwareProcessCtrl(true,cfgInfo.iCarWindowDetect,cfgInfo.iDevDirect + 1);
        }
        m_bResetProcess = false;
        m_bProcessStart = true;

    } else if (iCmd == Process_End) {
        InfoL << "业务流程复位，伸缩装置开始复位";
        m_bResetProcess = true;
        if ((m_iCurrentProcess == WAIT_PAGE) || (m_iCurrentProcess == CARD_READING_SUC) ||
        (m_iCurrentProcess == VEHICLE_PASSAGE) || (m_iCurrentProcess == VEHICLE_EXIT_CHANNEL) ||
        (m_iCachedProcess == VEHICLE_PASSAGE) || (m_iCachedProcess == VEHICLE_EXIT_CHANNEL) || (m_iCurrentProcess == Process_End)) {
            //TODO伸缩装置复位，流程复位,判断护照是否拿走，如未拿走超时等待，超时后收回装置
            InfoL << "m_iOCRDeviceState: " << m_iOCRDeviceState << ", m_bResetCollectionEgg:" << m_bResetCollectionEgg;
            if ((m_iOCRDeviceState != OCR_Removed) && (!m_bResetCollectionEgg) && (m_iOCRDeviceState > 0)) {
                InfoL << "证件未拿走，进入超时提示取走证件流程";
                m_bResetCollectionEgg = false;
                ocrTakeawayEvent(0);
            } 
            else {
                InfoL << "采集蛋执行复位<<<<<<<<<<<<<<<<<<<<<<<<";
                hardwareProcessCtrl(false,cfgInfo.iCarWindowDetect,cfgInfo.iDevDirect + 1);
                m_bResetCollectionEgg = true;
                m_bProcessStart = false;
            }
        } else  {
            InfoL << "执行采集蛋复位操作";
            hardwareProcessCtrl(false,cfgInfo.iCarWindowDetect,cfgInfo.iDevDirect + 1);
            m_bProcessStart = false;
        } 
        // else {
        //         InfoL << "采集蛋执行复位";
        //         hardwareProcessCtrl(false,cfgInfo.iCarWindowDetect,cfgInfo.iDevDirect + 1);
        //         m_bResetCollectionEgg = true;
        // }
    }
    m_iCurrentProcess = iCmd;
}

//接收硬件服务数据
void mv::TaskMgr::receiveSharememoryData(const int iType, const std::string sData) {
    InfoL << "sharememory type: " << iType << " revMsg: " << sData;
    if (iType == 1) {               //OCR连接状态
        m_bOCRConnect = static_cast<bool>(std::stoi(sData));
        if (m_bOCRConnect) {
            InfoL << "OCR连接状态: 已连接";
        } else {
            InfoL << "OCR连接状态: 断开连接";
        }

        parseOCRConnctStatus(m_bOCRConnect);
    } else if (iType ==2) {   //OCR目前刷证状态
        //m_iOCRState = std::stoi(sData);
        parseOCRStatus(std::stoi(sData));
    } else if (iType == 3) {  //OCR刷取数据
        InfoL << "OCR读取数据 m_sOCRData:" << sData;
        parseDocInfo(sData);
    } else if (iType == 4) {    //返回键按下
        //TODO回退流程，人脸虹膜流程回退到刷证，刷证回退到按人数，按人数无响应，清除对应缓存
        if (m_iCurrentProcess == FACE_REC || m_iCurrentProcess == IRIS_REC) {
            //关闭虹膜采集，发送切换到刷证流程,清除刷证数据，文件，以及采集的人脸数据
            backToSwipeProcess();
        } else if ((m_iCurrentProcess == CARD_READING) || (m_iCurrentProcess == CARD_READING_FAILED) || 
            (m_iCurrentProcess == CARD_STOP_MOVE)) {
            //切换到按人数页面，若时右舵停留在刷证页面,清除刷证数据
            if (cfgInfo.iDevDirect == 0) {
                backToEnterPeopleProcess();
            } else {
                InfoL << "右舵不处理回退到申报人数流程，跳过操作";
            }
        } else {
            InfoL << "非回退处理流程，跳过操作";
        }
    } else if (iType == 5) {    //采集蛋准备伸出，升降高度上传
        // m_iLeftHighAltitude = std::stoi(sData);
    } else if (iType == 6) {    //机械臂伸出到位
        //TODO切换提示按人数 --不做处理即可
        // if (m_iCurrentProcess == Process_Start || m_iCurrentProcess == GET_VEHICLE_INFO || m_iCurrentProcess == Process_End) {
        //     if (m_iStartNumOfPerson > 0) {
        //         awtkUISwitch(CARD_READING);
        //     } else {
        //         awtkUISwitch(Enter_Num_People);
        //     }
        // } else {
        //     InfoL << "非采集蛋伸出处理流程，跳过操作";
        // }
    } else if (iType == 7) {    //按键人数上传
        // if (m_iCurrentProcess == Enter_Num_People) {
        //     if (std::stoi(sData) == 1) {
        //         awtkUISwitch(CARD_READING);
        //     } else if (std::stoi(sData) == 2) {
        //         awtkUISwitch(Psg_Roll_Window);
        //         triggerOnceThread(CARD_READING);
        //     } else {
        //         awtkUISwitch(CARD_READING);
        //     }
            // pushPersonNumberData(sData,std::to_string(m_iLeftHighAltitude));
        // } else {
        //     InfoL << "非按键人数流程，跳过操作";
        // }
    } else if (iType == 8) {   //人脸采集成功
        if (m_iCurrentProcess == FACE_REC) {
            std::vector<std::string> sCmdLst = SplitString(sData,",");
            std::string sFaceData = sendHttpRequest(Request_Face);
            sFaceData  = sCmdLst[1] + "," + sCmdLst[2] + "," + sCmdLst[5] + "," + sCmdLst[4] + "," + sFaceData + 
            "," + "Y" + "," + sCmdLst[3];
            pushFaceData(sFaceData); 
            awtkUISwitch(Psg_UpDown_Tip);
            triggerOnceThread(IRIS_REC);
            //awtkUISwitch(IRIS_REC);
        }
    } else if (iType == 9) {   //人脸采集失败
        if (m_iCurrentProcess == FACE_REC) {
            std::string sFaceData = sendHttpRequest(Request_Face);
            sFaceData = "0,0,0,0," + sFaceData + ",Y," + "0";
            pushFaceData(sFaceData);
            //awtkUISwitch(IRIS_REC);
            awtkUISwitch(Psg_UpDown_Tip);
            triggerOnceThread(IRIS_REC);
       }
    } else if (iType == 10) { //虹膜采集成功
        if (m_iCurrentProcess == IRIS_REC) {
            std::vector<std::string> sCmdLst = SplitString(sData,",");
            std::string sIrisPic = sendHttpRequest(Request_Iris);
            std::string sEyeLeftpic = sendHttpRequest(Request_IrisLeft);
            std::string sEyeRightpic = sendHttpRequest(Request_IrisRight);
            std::string sIrisData = sCmdLst[4] + "," + sCmdLst[2] + "," + sCmdLst[3] + "," + sCmdLst[1] + "," + "Y," + 
            sIrisPic + "," + sEyeLeftpic + "," + sEyeRightpic;
            pushIrisData(sIrisData);
            m_bWaitingRelease = true;
            if ((m_iOCRDeviceState != OCR_Removed) && (m_iOCRDeviceState > 0)) {
                awtkUISwitch(CARD_READING_SUC);
                //ocrTakeawayEvent(0);
            } else {
                awtkUISwitch(WAIT_PAGE);
            }
        }
    } else if (iType == 11) { //虹膜采集失败
        if (m_iCurrentProcess == IRIS_REC) {
            std::vector<std::string> sCmdLst = SplitString(sData,",");
            std::string sIrisPic = sendHttpRequest(Request_Iris);
            std::string sEyeLeftpic = sendHttpRequest(Request_IrisLeft);
            std::string sEyeRightpic = sendHttpRequest(Request_IrisRight);
            
            if (std::stoi(sCmdLst[2]) > 0) {
                InfoL << "虹膜超时采集,未通过阈值判断";
            } else {
                InfoL << "虹膜超时采集,截取固定坐标图片";
            }
            //std::string sIrisData = "0,0,0,0,Y," + sIrisPic + "," + sEyeLeftpic + "," + sEyeRightpic;
            std::string sIrisData = sCmdLst[4] + "," + sCmdLst[2] + "," + sCmdLst[3] + "," + sCmdLst[1] + "," + "Y," + 
            sIrisPic + "," + sEyeLeftpic + "," + sEyeRightpic;
            pushIrisData(sIrisData);
            m_bWaitingRelease = true;
            if ((m_iOCRDeviceState != OCR_Removed) && (m_iOCRDeviceState > 0)) {
                awtkUISwitch(CARD_READING_SUC);
                //ocrTakeawayEvent(0);
            } else {
                awtkUISwitch(WAIT_PAGE);
            }
        }
    } else if (iType == 12) {
        parseAcquisitionCabinetStatus(static_cast<bool>(std::stoi(sData)));
    }else if (iType == 13){
        std::vector<std::string>  diatancePara = SplitString(sData,",");
        int height= std::stoi(diatancePara[0]);
        int width= std::stoi(diatancePara[1]);
        pushVehicleDistance(height,width);
    }
}

//解析采集柜下位机连接状态
void mv::TaskMgr::parseAcquisitionCabinetStatus(bool bConnect) {
    m_bAcquisitionCab = bConnect;

    if (m_bAcquisitionCab) {
        InfoL << "采集蛋下位机已连接";
        //if ((m_iCurrentProcess == EQUIPMENT_ABNORMALITY) || (m_bUDPConnect && m_bOCRConnect)) {
        if (m_bUDPConnect && m_bOCRConnect) {
            awtkUISwitch(WELCOME_PAGE);
            std::string sData = "0,1,0,0,1,0";
            pushTerminalStatus(sData);
        } else if (!m_bUDPConnect) {
            InfoL << "UDP Push 通讯断开连接<";
            awtkUISwitch(CLOSE_PAGE);
            hardwareLightCtrl(Light_Red);
        }
    } else {
        InfoL << "采集蛋下位机已断开";
        if (((m_iCurrentProcess == EQUIPMENT_ABNORMALITY) || (m_iCurrentProcess == -1)) && (m_iOCRState == -1)) {
            //未收到OCR状态，且已处于设备故障页面
            InfoL << "等待查询OCR连接状态<<";
        } 
        // else if (m_iCurrentProcess == EQUIPMENT_ABNORMALITY) {
        //     //已收到OCR状态，且已经处于系统故障页面
        //     InfoL << "当前已处于设备故障页面，跳过操作<<";
        // } 
        else {
            //直接切换系统故障页面
            int iOCRState = -1;
            if (m_bOCRConnect) {
                iOCRState = 1;
            } else {
                iOCRState = 2;
            }
            std::string sData = "0," + std::to_string(iOCRState) + ",0,0,2,0"; 
            pushTerminalStatus(sData);

            awtkUISwitch(EQUIPMENT_ABNORMALITY);
            hardwareLightCtrl(Light_Red);
        }
    }
}

//解析OCR连接状态
void mv::TaskMgr::parseOCRConnctStatus(bool bConnect) {
    m_bOCRConnect = bConnect;
    
    if (m_bOCRConnect) {
        if ((m_iCurrentProcess == EQUIPMENT_ABNORMALITY) || (m_bUDPConnect && m_bAcquisitionCab)) {
            awtkUISwitch(WELCOME_PAGE);

            std::string sData = "0,1,0,0,1,0";
            pushTerminalStatus(sData);
        } else if (m_iCurrentProcess != EQUIPMENT_ABNORMALITY) {
            if ((!m_bAcquisitionCab) && (m_iOCRState == -1)) {
                InfoL << "系统启动初始化，下位机连接异常<<<";

                std::string sData = "0,1,0,0,2,0";
                pushTerminalStatus(sData);

                awtkUISwitch(EQUIPMENT_ABNORMALITY);
                hardwareLightCtrl(Light_Red);
            }
        }
    } else {
            int iAcquisitionCab = -1;
            if (m_bAcquisitionCab) {
                iAcquisitionCab = 1;
            } else {
                iAcquisitionCab = 2;
            }

            std::string sData = "0,2,0,0,"+ std::to_string(iAcquisitionCab) +",0"; 
            pushTerminalStatus(sData);

            awtkUISwitch(EQUIPMENT_ABNORMALITY);
            hardwareLightCtrl(Light_Red);
    }
    m_iOCRState = static_cast<int>(bConnect);
}

//解析OCR刷取状态
void mv::TaskMgr::parseOCRStatus(const int iStatus) {
    if (iStatus == 2) {        //正在读取，证件放上
        InfoL << "证件读取中..........................................";
        m_iOCRDeviceState = iStatus;

        if (m_iCurrentProcess == CARD_READING || m_iCurrentProcess == CARD_STOP_MOVE ||
            m_iCurrentProcess == CARD_READING_FAILED) {
            awtkUISwitch(CARD_STOP_MOVE);
        }

        //暂时加上处理在收到放行指令过程中，来回切换提示取回证件流程
        if ((m_bWaitingRelease) && (!m_bResetCollectionEgg)) {
            awtkUISwitch(CARD_READING_SUC);
        }

    } else if (iStatus == 3) {        //证件拿走
        InfoL << "证件移开..........................................";
        m_iOCRDeviceState = iStatus;

        //判断是否在提示证件拿走流程
        if ((m_bTakeAwayPassport || m_bWaitingRelease) && m_bResetProcess) {
            InfoL << "证件移开,采集蛋待收回流程,执行收回操作";
            ocrTakeawayEvent(1);
        } else if ((m_bWaitingRelease) && (!m_bResetCollectionEgg) && (!m_bResetProcess)) {
            InfoL << "证件移开,采集蛋未收回，切请等待.";
            awtkUISwitch(WAIT_PAGE);
        } else {
            InfoL << "证件移开,非采集蛋复位流程.";
        }
    }
}

//上传OCR信息相关
void mv::TaskMgr::uploadOcrInfo(const int iFlag, const std::string sInfo) {
    if (iFlag == 0) {               //刷证超时
        InfoL << "刷证超时 <<<<<<<<<<<<<<<<<<<<";
        m_bOcrTimeOProcess = false;
        m_iOcrCurntTimeInc = 0;
        pushOCRData(0,sInfo);
        awtkUISwitch(WAIT_PAGE);
    } else if (iFlag == 1) {   //刷证成功
        //http获取OCR图片相关信息
        std::vector<std::string> sCmdLst = SplitString(sInfo,",");
        picInfo.m_sFaceScreenPic = sendHttpRequest(Request_FaceScrshot);
        picInfo.m_sIDPhotoPic = sendHttpRequest(Request_IDPhoto);
        picInfo.m_sElectronicPic = sendHttpRequest(Request_Electronic);

        //组装发送信息
        std::string sSendData = sCmdLst[1] + "," + sCmdLst[2];
        for (size_t i = 3; i <= 8; i++)
        {
            sSendData = sSendData + "," + sCmdLst[i];
        }

        sSendData = sSendData + "," + picInfo.m_sIDPhotoPic + "," + picInfo.m_sFaceScreenPic + "," + picInfo.m_sElectronicPic + "," + 
            cfgInfo.sLocalIP + "," + cfgInfo.sTerminalMac;
        
        m_bOcrTimeOProcess = false;
        m_iOcrCurntTimeInc = 0;
        //pushOCR相关信息
        pushOCRData(1,sSendData);
    }
}

//解析ocr数据
void mv::TaskMgr::parseDocInfo(const std::string sData) {
    if(m_iCurrentProcess == CARD_READING || m_iCurrentProcess == CARD_STOP_MOVE || m_iCurrentProcess == CARD_READING_FAILED){
        //先接收到证件读取状态再读取到证件信息、上传证件信息
        std::vector<std::string> sCmdLst = SplitString(sData,",");
        if (std::stoi(sCmdLst[0]) == 0) {
            awtkUISwitch(CARD_READING_FAILED);
        } else {
            awtkUISwitch(CARD_READING_SUC);

            uploadOcrInfo(1,sData);

            InfoL << "Swtich face rec";
            //延时1秒发送人脸验证
            triggerOnceThread(FACE_REC);
            InfoL << "Swtich face rec <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<";
        }
    } else {
        InfoL << "非证件读取流程--跳过操作";
    }
}

//执行业务端流程切换
//车停稳 流程开始 -- 伸缩到位 -- 切换按人数  -- 刷证 -- 人脸 -- 虹膜 -- 验放 -- 复位
void mv::TaskMgr::awtkUISwitch(const int iCmd) {
    InfoL << "<<<<<<<<<<<<<<<<<<<<<<<<<<";
    switch (iCmd)
    {
    case WELCOME_PAGE:
        InfoL << "切换到首页" ;
        initTaskParameter();

        pubAwtkProcessEvent(WELCOME_PAGE);
        break;

    case GET_VEHICLE_INFO:
        InfoL << "切换到车牌识别页面--提示司机摇下车窗" ;
        pubAwtkProcessEvent(GET_VEHICLE_INFO);
        break;

    case Enter_Num_People:
        InfoL <<"切换到请输入车内人数页面";
        pubAwtkProcessEvent(Enter_Num_People);
        break;

    case CARD_READING:
        InfoL <<"切换到刷证件页面";
        pubAwtkProcessEvent(CARD_READING);
        break;

    case CARD_STOP_MOVE:
        InfoL << "切换到请勿移动证件页面";
        pubAwtkProcessEvent(CARD_STOP_MOVE);
        break;
    
    case CARD_READING_FAILED:
        InfoL << "切换到读卡失败页面";
        pubAwtkProcessEvent(CARD_READING_FAILED);
        break;

    case CARD_READING_SUC:
        InfoL << "切换到请取回护照页面";
        pubAwtkProcessEvent(CARD_READING_SUC);
        break;

    case FACE_REC:
        InfoL << "切换到人脸识别页面";

        if (!m_bOpenIrisCamera) {
            m_bOpenIrisCamera = true;
        }

        pubAwtkProcessEvent(FACE_REC);
        faceirisAcProcess(FACE_REC);
        //hardwareLightCtrl(Light_White);
        break;

    // case FACE_REC_FULL_SCREEN:
    //     pubAwtkProcessEvent(FACE_REC_FULL_SCREEN);
    //     break;

     case IRIS_REC:
        InfoL << "切换到虹膜识别页面";

        if (!m_bOpenIrisCamera) {
            m_bOpenIrisCamera = true;
        }

        pubAwtkProcessEvent(IRIS_REC);
        faceirisAcProcess(IRIS_REC);
        //hardwareLightCtrl(Light_Close);
        break;

    // case IRIS_REC_FULL_SCREEN:
    //     pubAwtkProcessEvent(IRIS_REC_FULL_SCREEN);
    //     break;
    case GET_VEHICLE_FAILED:
        InfoL << "切换到车牌识别失败页面";
        pubAwtkProcessEvent(GET_VEHICLE_FAILED);
        break;

    case WAIT_PAGE:
        InfoL << "切换到请稍等页面";
        pubAwtkProcessEvent(WAIT_PAGE);
        break;

    case VEHICLE_PASSAGE:
        InfoL << "切换到车辆通行页面";
        m_bWaitingRelease = false;
        m_bOcrTimeOProcess = false;
        m_bTakeAwayPassport = false;
        pubAwtkProcessEvent(VEHICLE_PASSAGE);
        hardwareLightCtrl(Light_Green);
        break;

    case VEHICLE_EXIT_CHANNEL:
        InfoL << "切换到车辆退车页面";
        m_bWaitingRelease = false;
        m_bOcrTimeOProcess = false;
        m_bTakeAwayPassport = false;
        pubAwtkProcessEvent(VEHICLE_EXIT_CHANNEL);
        hardwareLightCtrl(Light_Red);
        break;

    case FACE_EXPIRED:
        InfoL << "切换到人脸采集失败页面";
        pubAwtkProcessEvent(FACE_EXPIRED);
        break;

    case IRIS_FAILED:
        InfoL << "切换到虹膜采集失败页面";
        pubAwtkProcessEvent(IRIS_FAILED);
        break;

    case CLOSE_PAGE:
        InfoL << "切换到通道关闭，暂停服务页面";
        pubAwtkProcessEvent(CLOSE_PAGE);
        break;

    case EQUIPMENT_ABNORMALITY:
        InfoL << "切换到设备故障页面";
        pubAwtkProcessEvent(EQUIPMENT_ABNORMALITY);
        break;

    case Psg_Roll_Window:
        InfoL << "切换到乘客摇下车窗页面";
        pubAwtkProcessEvent(Psg_Roll_Window);
        break;

    case Psg_UpDown_Tip:
        InfoL << "切换到旅客上下摇杆升降页面";
        pubAwtkProcessEvent(Psg_UpDown_Tip);
        break;

    default:
        break;
    }

    if(iCmd == WELCOME_PAGE || iCmd == CLOSE_PAGE || iCmd == WAIT_PAGE || iCmd == CARD_READING
    || iCmd == Enter_Num_People || iCmd == CARD_READING_SUC || iCmd == VEHICLE_PASSAGE || iCmd == VEHICLE_EXIT_CHANNEL || 
    m_iCurrentProcess == Process_End || m_iCurrentProcess == Process_Start) {
        //假如在人脸虹膜流程，关闭摄像头
        if (m_bOpenIrisCamera) {
            m_bOpenIrisCamera = false;
            irisCameraCloseCtrl();
        }
    }

    if (iCmd != CARD_READING) {
        // if (m_bOcrTimeOProcess) {
        //     m_bOcrTimeOProcess = false;
        //     m_iOcrCurntTimeInc = 0;
        // }
    } else {
        if (!m_bOcrTimeOProcess) {
            m_bOcrTimeOProcess = true;
            m_iOcrCurntTimeInc = 0;
        }
    }

    m_iCurrentProcess = iCmd;
}

//-------------------------------------------------------------------------------------
void mv::TaskMgr::initListionTask() {
    //初始化心跳接口
    initHeartbeatTasks();

    //注册回复消息
    toolkit::NoticeCenter::Instance().addListener(0, "udp_push_process", &recvPushData);
    toolkit::NoticeCenter::Instance().addListener(0, "udp_push_status", &recvPushConnect);
    toolkit::NoticeCenter::Instance().addListener(0, "shm_sub_data", &recvShmMsg);

    //初始化共享内存
    initSharememoryInterface();

    //初始化参数
    initCfgTask();

    //执行OCR超时计时线程
    ocrProcessTimeOutEvent();

    //获取OCR状态
    if (!m_bOCRConnect) {
        getOcrConnectionStatus();
    }
}

//读取配置文件
void mv::TaskMgr::initCfgTask() {
    //读取json配置文件
    std::string sRevCfg =  readJsonConfig("/root/mvAcquisitionServer/config.json");

    std::vector<std::string> sCmdLst = SplitString(sRevCfg,",");

    //获取本地IP和MAC地址
    cfgInfo.sLocalIP =  getLocalIP();
    cfgInfo.sTerminalMac=  getLocalMacAddress();

    cfgInfo.iCardReadTimeout = std::stoi(sCmdLst[0]);
    cfgInfo.iCarWindowDetect = std::stoi(sCmdLst[1]);
    cfgInfo.iPushPort = std::stoi(sCmdLst[3]);
    cfgInfo.iPlatformPort = std::stoi(sCmdLst[5]);
    cfgInfo.sPlatformInterface = sCmdLst[6];
    cfgInfo.sPlatformIP = sCmdLst[4];
    cfgInfo.sPushIP =sCmdLst[2];
    cfgInfo.iDevDirect = std::stoi(sCmdLst[7]);
    cfgInfo.iTakeAwayCardTimeout = std::stoi(sCmdLst[8]);

    //初始化push通讯
    char * localIP = new char[cfgInfo.sLocalIP.length() + 1];
    char * pushIP = new char[sCmdLst[2].length() + 1];
    strcpy(localIP, cfgInfo.sLocalIP.c_str());
    strcpy(pushIP, sCmdLst[2].c_str());

    InfoL << "localIP: " << cfgInfo.sLocalIP << " pushIP:" << cfgInfo.sPushIP << " mac:" << cfgInfo.sTerminalMac;

    setLocalClientID(cfgInfo.sLocalIP);
    Push_Connect(localIP,pushIP,cfgInfo.iPushPort);

    mv::HttpCurlMgr::getSingleton()->setUploadPath(cfgInfo.sPlatformInterface,cfgInfo.sPlatformIP,cfgInfo.iPlatformPort);

//清除char*缓存
    delete[] localIP;
    delete[] pushIP;
}

//初始化流程参数
void mv::TaskMgr::initTaskParameter() {
    //初始化各流程参数
    InfoL << "initTaskParameter <<<<<<<<<<<<<";

    if (m_bOpenIrisCamera) {
        m_bOpenIrisCamera = false;
        irisCameraCloseCtrl();
    }
    //关报警灯
    hardwareLightCtrl(Light_Close);

    m_bProcessStart = false;
    m_bOpenIrisCamera = false;
    m_bWaitingRelease = false;
    m_bResetProcess = false;
    m_bResetCollectionEgg = false;
    m_bOcrTimeOProcess = false;
    m_bTakeAwayPassport = false;
    m_iLeftHighAltitude = 0;
    m_iNumberOfPerson = 0;
    m_iStartNumOfPerson = 0;
    m_iOcrCurntTimeInc = 0;
    m_iTakeAwIDInc = 0;
    m_iOCRDeviceState = -1;
    m_iCachedProcess = -1;

    //流程初始化 1、判断是否执行了采集蛋收回指令，未执行的情况发送采集蛋收回
    // if (!m_bResetCollectionEgg) {
    //     hardwareProcessCtrl(false,cfgInfo.iCarWindowDetect);
    // }

    //删除各个缓存文件
    clearImageData();
}

//初始化心跳接口
void mv::TaskMgr::initHeartbeatTasks() {
    	heartbeat_interface_init("mvAcquisitionServer");
		int m_interval = 20;
		heartbeat_interface_set_interval(m_interval);
		heartbeat_interface_start_detect();
		m_bPauseThread = true;
		std::thread sliderThread([=](){
			std::chrono::seconds interval(6); 
			while (m_bPauseThread) {
                std::this_thread::sleep_for(interval); 
                heartbeat_interface_send();
			}
		});
		sliderThread.detach();
}

std::string mv::TaskMgr::sendHttpRequest(const int iFlag) {
    //判断文件是否在，不在返回"" ,在的话申请图片接口返回图片加密字符串
    std::string sfilePath = "";
    if (iFlag == Request_Face) {
        sfilePath = "/userdata/CapImage/face.png";
    } else if (iFlag == Request_Iris) {
        sfilePath = "/userdata/CapImage/iris.jpg";
    } else if (iFlag == Request_IrisLeft) {
        sfilePath = "/userdata/CapImage/eye_left.png";
    } else if (iFlag == Request_IrisRight) {
        sfilePath = "/userdata/CapImage/eye_right.png";
    } else if (iFlag == Request_IDPhoto) {
        sfilePath = "/userdata/image/photo6.jpg";
    } else if (iFlag == Request_FaceScrshot) {
        sfilePath = "/userdata/image/photo10.jpg";
    } else if (iFlag == Request_Electronic) {
        sfilePath = "/userdata/image/photo20.jpg";
    }

    //判断文件是否存在，不存在就返回空字符串
    if (!fileExists(sfilePath)) {
        return "";
    }

    //推送照片路径请求加密字符串
    std::string revRequest = mv::HttpCurlMgr::getSingleton()->httpPostFile(sfilePath,m_sVehicleNo);
    InfoL << "fileFlag: " << iFlag << " filepath: " << sfilePath;
    InfoL << "sendHttpRequest rev: " << revRequest;
    return  revRequest;
}

//返回刷证件流程
void mv::TaskMgr::backToSwipeProcess() {
    InfoL << "backToSwipeProcess: " << "FACE->Card";
    // if (m_bOpenIrisCamera) {
    //     irisCameraCloseCtrl();
    //     m_bOpenIrisCamera = false;
    // }
    hardwareLightCtrl(Light_Close);
    clearImageData();
    m_bOcrTimeOProcess = false;
    m_iOcrCurntTimeInc = 0;
    awtkUISwitch(CARD_READING);
}

//返回按人数流程
void mv::TaskMgr::backToEnterPeopleProcess() {
        InfoL << "backToEnterPeopleProcess: " << "Card->Enterpeople";
        clearImageData();
        m_bOcrTimeOProcess = false;
        m_iOcrCurntTimeInc = 0;
        m_iNumberOfPerson = 0;
        m_iStartNumOfPerson = 0;
        awtkUISwitch(Enter_Num_People);
}

void mv::TaskMgr::clearImageData() {
    //删除各个缓存文件
    fileDelete("/userdata/CapImage/face.png");
    fileDelete("/userdata/CapImage/iris.jpg");
    fileDelete("/userdata/CapImage/eye_left.png");
    fileDelete("/userdata/CapImage/face.png");
    fileDelete("/userdata/CapImage/eye_right.png");
    fileDelete("/userdata/CapImage/face_onsite.jpg");
    fileDelete("/userdata/image/photo6.jpg");
    fileDelete("/userdata/image/photo10.jpg");
    fileDelete("/userdata/image/photo20.jpg");
    fileDelete("/userdata/image/photo11.jpg");
    fileDelete("/userdata/image/photo4.jpg");   
}

//-------------------------------------------------------------------------------------
mv::TaskMgr::TaskMgr() {
	m_pTasIpcPool = new toolkit::ThreadPool(1, toolkit::ThreadPool::PRIORITY_HIGHEST, true);
	m_pTaskResultPool = new toolkit::ThreadPool(1, toolkit::ThreadPool::PRIORITY_HIGHEST, true);
}

//-------------------------------------------------------------------------------------
mv::TaskMgr::~TaskMgr() {
    m_bPauseOCRThread = false;
    m_bPauseThread = false;
}
//-------------------------------------------------------------------------------------

void mv::TaskMgr::onceThreadFunc(const int iCmd) {
    //std::this_thread::sleep_for(std::chrono::seconds(2));
    if (iCmd == FACE_REC) {
        std::this_thread::sleep_for(std::chrono::seconds(2));
        if (m_iCurrentProcess == CARD_READING_SUC) {
            awtkUISwitch(iCmd);
        }
    } else if (m_iCurrentProcess == Psg_UpDown_Tip) {
        std::this_thread::sleep_for(std::chrono::seconds(7));
        if (m_iCurrentProcess == Psg_UpDown_Tip) {
            awtkUISwitch(iCmd);
        }
    } else if (m_iCurrentProcess == Psg_Roll_Window) {
        std::this_thread::sleep_for(std::chrono::seconds(5));
        if (m_iCurrentProcess == Psg_Roll_Window) {
            awtkUISwitch(iCmd);
        }
    } else {
        std::this_thread::sleep_for(std::chrono::seconds(2));
        awtkUISwitch(iCmd);
    }
    InfoL << "onceThreadFunc: " << iCmd;
}

void mv::TaskMgr::triggerOnceThread(const int iFunc) { 
    std::thread oneShotThread(&mv::TaskMgr::onceThreadFunc, this, iFunc);
    //oneShotThread.join();
    oneShotThread.detach();//分离主线程,后台运行
}

void mv::TaskMgr::ocrProcessTimeOutEvent() {
    std::thread ocrTimeoutThread([=]() {
        std::chrono::seconds interval(1); 
        while (m_bPauseOCRThread)
        {
            //TODO 采用计数方式，来计读证超时
            std::this_thread::sleep_for(interval); 
            if (m_bOcrTimeOProcess) {
                m_iOcrCurntTimeInc ++;
                printf("Swipe time :%d \n",m_iOcrCurntTimeInc);
                if (m_iOcrCurntTimeInc == cfgInfo.iCardReadTimeout) {
                    uploadOcrInfo(0,"");
                }
            }

            if (m_bTakeAwayPassport) {
                m_iTakeAwIDInc ++;
                printf("TakeAway time :%d \n",m_iTakeAwIDInc);
                if (m_iTakeAwIDInc == cfgInfo.iTakeAwayCardTimeout) {
                    ocrTakeawayEvent(1);
                }
            }
        }
    });
    ocrTimeoutThread.detach();
}

//拿走证件处理事件 0信息采集完成未拿走，1强行结束提示拿走证件流程
void mv::TaskMgr::ocrTakeawayEvent(const int iFlag) {
    InfoL << "ocrTakeawayEvent: " <<  iFlag;
    if (iFlag == 1) {
        if (m_iCachedProcess == VEHICLE_EXIT_CHANNEL) {
            awtkUISwitch(VEHICLE_EXIT_CHANNEL);
        } else if (m_iCachedProcess == VEHICLE_PASSAGE) {
            awtkUISwitch(VEHICLE_PASSAGE);
        } else {
            awtkUISwitch(WAIT_PAGE);
        }
        if (m_bResetProcess) {
            InfoL << "ocrTakeawayEvent:执行采集蛋复位流程";
            m_bResetCollectionEgg = true;
            hardwareProcessCtrl(false,cfgInfo.iCarWindowDetect,cfgInfo.iDevDirect + 1);
            m_bProcessStart = false;
        }
        m_bTakeAwayPassport = false;
        m_iTakeAwIDInc = 0;
    } else {
        m_bTakeAwayPassport = true;
        m_iTakeAwIDInc = 0;
    }
}